<?php

namespace app\admin\controller\sport;

use app\common\controller\Backend;
use think\Db;
use think\db\exception\BindParamException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\sport\ScoreType;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

/**
 * 评分项目设置
 *
 * @icon fa fa-circle-o
 */
class Score extends Backend
{

    /**
     * Score模型对象
     * @var \app\admin\model\sport\Score
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\sport\Score;
        $this->view->assign("scoreTypeList", $this->model->getScoreTypeList());
        $this->view->assign("sexList", $this->model->getSexList());
        $this->view->assign("unitList", $this->model->getUnitList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->field('id, sport_area_id, sport_type_id, score_type, sex, project_name, unit, show_unit, show_val, status, weigh, createtime, updatetime')  // 指定需要的字段
            ->where($where)
            ->with(['area', 'stype'])
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        if ($params['score_type'] == 'middle' && empty($params['sport_type_id'])) {
            $this->error('中考必须选择项目类别');
        }
        // 判断输入点不能超过3个, 替换全角的点的可能
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            if (empty($params['weigh'])) {
                $params['weigh'] = Db::table('sport_score')->max('id') + 1;
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            // 查找对应的项目类别
            $sportTypes = ScoreType::where('sport_area_id', $row->sport_area_id)->select();
            $types = ['0' => '无'];
            foreach ($sportTypes as $t) {
                $types[$t->id] = $t->type_name;
            }
            $setting = json_decode($row->score_setting, true);
            $this->view->assign('typeList', $types);
            $this->view->assign('row', $row);
            $this->view->assign('num', !empty($setting) ? count($setting) : 0);
            
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($params['score_type'] == 'middle' && empty($params['sport_type_id'])) {
            $this->error('中考必须选择项目类别');
        }
        // 判断输入点不能超过3个, 替换全角的点的可能
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function import()
    {
        if (false === $this->request->isPost()) {
            $this->view->assign('score_id', input('get.sport_score_id'));
            $templateFile = cdnurl('/template/评分标准导入模版.xlsx', true);
            $this->view->assign('template_file', $templateFile);
            return $this->view->fetch();
        }
        $res = [
            'msg' => '评分标准导入成功',
            'err' => [],
        ];
        $scoreId = input('post.score_id');
        $file = input('post.file');
        $filePath = ROOT_PATH . 'public' . $file;
        if (!is_file($filePath)) {
            $this->error(__('文件不存在'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        $insert = [];
        try {
            $row = $this->model->get($scoreId);
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            // 表头
            for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }
            $scoreSetting = [];
            // 数据
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = $val === '' || trim($val) === '-' ? '' : trim($val);
                }
                // var_dump($values);
                // 检查数据
                $min = trim($values[0]);
                $max = trim($values[1]);
                $score = trim($values[2]);
                if ($min == '' && $max == '') {
                    $res['err'][] = '第' . $currentRow . '行缺失分值范围';
                    continue;
                }
                if ($score == '') {
                    $res['err'][] = '第' . $currentRow . '行缺失得分';
                    continue;
                }
                if ($min == '' && !empty($max)) {
                    $min = $max;
                } else if (!empty($min) && $max == '') {
                    $max = $min;
                }
                // 如果导入时有显示单位是要两个点，但本身不是两个点，给他补全两个点
                $showUnit = $row->show_unit;
                $dotUnitTotal = mb_substr_count($showUnit, ".");
                if ($dotUnitTotal == 2) {
                    $dotMinTotal = mb_substr_count($min, ".");
                    $dotMaxTotal = mb_substr_count($max, ".");
                    if ($dotMinTotal != $dotUnitTotal) {
                        $min .= ".00";
                    }
                    if ($dotMaxTotal != $dotUnitTotal) {
                        $max .= ".00";
                    }
                }
                $scoreSetting[] = [
                    'min'  => $min,
                    'max'  => $max,
                    'score' => $score,
                ];
            }
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (empty($scoreSetting)) {
            $res['err'][] = '没有要导入的评分标准';
        }
        if (empty($res['err'])) {
            try {
                $row->score_setting = json_encode($scoreSetting);
                $row->save();
            } catch (PDOException $exception) {
                $msg = $exception->getMessage();
                $this->error($msg);
            } catch (Exception $e) {
                $this->error($e->getMessage());
            }
        } else {
            $res['msg'] = '导入失败';
        }
        $this->success('ok', null, $res);
        
    
    }

}
